package com.demo.crm.springboot3security.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import com.demo.crm.springboot3security.util.TraceIdUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 请求链路ID拦截器
 */
public class TraceIdInterceptor implements HandlerInterceptor {

    private static final String TRACE_ID_HEADER = "X-Trace-Id";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 优先从请求头中获取链路ID
        String traceId = request.getHeader(TRACE_ID_HEADER);
        if (traceId == null || traceId.trim().isEmpty()) {
            // 如果请求头中没有，则生成新的链路ID
            traceId = TraceIdUtil.generateTraceId();
        }

        // 设置链路ID到MDC
        TraceIdUtil.setTraceId(traceId);

        // 将链路ID添加到响应头
        response.addHeader(TRACE_ID_HEADER, traceId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        // 请求完成后清除链路ID
        TraceIdUtil.clearTraceId();
    }
}